//
//  HLWebViewController.swift
//  MyBlog
//
//  Created by 李芙蓉 on 16/3/5.
//  Copyright © 2016年 hanlei. All rights reserved.
//

import UIKit

class HLWebViewController: UIViewController, UIWebViewDelegate {
    
    //AppKey
    var AppKey : String = "889700878"
    
    //redictUri
    var redictUri : String = "http://www.itheima.com/"
    
    //AppSecret
    var AppSecret : String = "7dd02764b35291e9506afc58b889dd20"
    
    //AppCode
    var code : String?
    
    //令牌
    var AccessToken : String?
    
    //懒加载webView
    var webView : UIWebView = {
    
        let w = UIWebView()
        
        return w
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: "backButtonDidClick")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动生成", target: self, action: "autoFillButtonDidClick")
        
        view = webView
        
        webViewDidLoad()
        
        webView.delegate = self
    }
    
    //实现webView的代理方法
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        if let queryString = request.URL?.query {
            
            if queryString.containsString(redictUri) {
                
                return true
            
            } else {
                
                code = queryString.substringFromIndex("code=".endIndex)
                
                HLOAuthViewModel.sharedOAuthViewModel.loadAccessToken(code!, appKey: AppKey, appSecret: AppSecret, redictUri: redictUri, callBack: { (success) -> () in
                    
                    if success {
                        
                        //跳转到欢迎控制器
                        print("我要跳转")
                    }
                })
            }
        }
        
        return true
    }
    
    //webView的网络请求方法
    private func webViewDidLoad () {
        
        let request = NSURLRequest(URL: NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(redictUri)")!, cachePolicy: .ReloadRevalidatingCacheData, timeoutInterval: 15)
        
        webView.loadRequest(request)
    }
    
    
    //返回按钮点击事件
    @objc private func backButtonDidClick () {
        
        self.dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    //自动生成按钮点击事件
    @objc private func autoFillButtonDidClick () {
        
        let javaScriptString = "document.getElementById('userId').value = 15071346799;document.getElementById('passwd').value = 'krm4sdul'"
        
        webView.stringByEvaluatingJavaScriptFromString(javaScriptString)
    }

}
